package pnu.ssm.broadcast;

import java.util.List;

import pnu.ssm.appinfo.AppInfo;
import pnu.ssm.appinfo.AppListHelper;
import pnu.ssm.http.HttpConnector;
import pnu.ssm.key.Key;
import pnu.ssm.sbchild.MainActivity;
import android.R;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GcmIntentService extends IntentService{
	public static final String TAG = "GcmIntentService() --- ";
	public static final int NOTIFICATION_ID = 1;
	public static final int ADD_RESPONSE_HANDLER = 2;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;

    public GcmIntentService() {
        super("GcmIntentService");
    }
    
    HttpConnector httpConnector = HttpConnector.getInstance();
    SharedPreferences pref;
    //Activity's Handler
    Messenger activityMessenger = null;
    
    //gcmHandler는 GCM Service의 핸들러다. 이 핸들러는 onBind메서드를 통해 Activity에게 넘겨진다.
    private Handler gcmHandler = new Handler(){
    	@Override
		public void handleMessage(Message msg) {
    		switch (msg.what) {
    		case ADD_RESPONSE_HANDLER:
    			activityMessenger = msg.replyTo;
    			break;
			default:
				Log.e(TAG, "GCM Service received message from activity!");
				break;
			}
    	};
    };
    Messenger gcmMessenger = new Messenger(gcmHandler);
    @Override
	public IBinder onBind(Intent intent) {
    	return gcmMessenger.getBinder();
    };

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
//                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
//                sendNotification("Deleted messages on server: "+extras.toString());
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
            	messageProcessor(extras.toString());
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
//                sendNotification("Received: " + extras.toString());
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        WakefulBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_dialog_alert)
        .setSmallIcon(R.drawable.ic_notification_clear_all)
        .setContentTitle("GCM Notification")
        .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
        .setContentText(msg);
        
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
    
    public void messageProcessor(String msg){
    	Log.d(TAG, "messageProcessor() -- msg : " + msg);
    	Message message = Message.obtain();
    	String[] splitMessage = msg.split(",");
    	String msgPrefix = splitMessage[0];
    	String token = "message=";
    	int index = msgPrefix.indexOf(token);
    	msg = msgPrefix.substring(index+token.length());
    	pref = getApplicationContext().getSharedPreferences(Key.prefKey, MODE_PRIVATE);
    	
//    	try {
    		if(msg.contains("ANDROID_FORBIDDEN")){
    			message.what = MainActivity.UPDATE_APP_LIST;
    			String child_num = pref.getString("child_num", null);
    			if(child_num != null){
    				List<AppInfo> appInfos = httpConnector.getForbiddenAppList(child_num);
    				AppListHelper appListHelper = AppListHelper.getInstance();
    				appListHelper.setForbiddenAppList(appInfos);
    				httpConnector.sendAppList(child_num, getApplicationContext());
    			}
    		}else if(msg.contains("ANDROID_CHINESE")){
//    			message.what = MainActivity.UPDATE_CHINESE_SETTING;
//    			pref = getApplicationContext().getSharedPreferences(Key.prefKey, MODE_PRIVATE);
//    			String child_num = pref.getString("child_num", null);
//    			if(child_num != null){
//    				httpConnector.sendAppList(child_num, getApplicationContext());
//    			}
    		}else{
    			
    		}
//			activityMessenger.send(message);
//		} catch (RemoteException e) {
//			e.printStackTrace();
		}
    }
//}
